#import "YQPInvitataionModel.h"

#import "MYDynamicDetailsVC.h"
#import "MYHomeAttentionImageCell.h"
#import "MYDynamicDetailsGoodsCell.h"
#import "MYDynamicCommentVC.h"
#import "MYShopDetailsVC.h"
#import "MYShardAlertSheet.h"
@interface MYDynamicDetailsVC ()<MYDynamicDetailsGoodsCellDelegate>
@property (nonatomic, assign) CGFloat goodsCellH;
//@property (nonatomic, strong) MYDynamicDetailsGoodsCell * goodsCell;

@property (nonatomic, strong) MYDynamicDetailsBottonView * bottonView;

@property (strong, nonatomic) YQPInvitataionModel *model;

@end

@implementation MYDynamicDetailsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = kYQLS(@"帖子详情");
    self.rightItemImage = YQIMG(@"nav_Right_more_icon");
    self.goodsCellH = 100;
    
    [self getUserInvitationsApi];
}

#pragma mark - 获取帖子详情
- (void)getUserInvitationsApi
{
    NSString *userID =  [Config currentConfig].userUid;
    if ([userID removeStringSpace].length == 0) {
        userID = @"0";
    }
    NSString *url = [NSString stringWithFormat:@"%@%@/%@/%@",kGET_TIE_INFO_URL,userID,self.invitationId,self.channelId];
    [YQPNetWorkingManager sendGetRequest:url parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        self.model = [YQPInvitataionModel mj_objectWithKeyValues:responseObject.data];
        NSString *callNum = [NSString stringWithFormat:@"%@ %@",kYQLS(@"点赞"),self.model.likeNumber];
        [self.bottonView.callBtn setTitle:callNum forState:UIControlStateNormal];

        NSString *likeNum = [NSString stringWithFormat:@"%@ %@",kYQLS(@"收藏"),self.model.collectNumber];
        [self.bottonView.likeBtn setTitle:likeNum forState:UIControlStateNormal];

        NSString *commentNum = [NSString stringWithFormat:@"%@ %zd",kYQLS(@"评论"),self.model.commentNumber];
        [self.bottonView.commentBtn setTitle:commentNum forState:UIControlStateNormal];

        //点赞状态
        if ([self.model.isLike isEqualToString:@"1"]) {
            self.bottonView.callBtn.selected = YES;
        }
        
        //收藏状态
        if ([self.model.isCollect isEqualToString:@"1"]) {
            self.bottonView.likeBtn.selected = self.model.isCollect.boolValue;
        }
        
        [self.listTableView reloadData];

    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        
    }];
}
/// kGET_INVITATION_SHIELD_URL
-(void)shieldTieApi {
    YQSHOWLOADINGTIPS(@"");
    [YQPNetWorkingManager sendGetRequest:kGET_INVITATION_SHIELD_URL(self.invitationId) parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code!=205) {
             if (responseObject.code == 0) {
                       YQUITIPSSUCCEED(kYQLS(@"屏蔽成功"))
                       if (self.updateListBlock) {
                           self.updateListBlock();
                       }
                       [self.navigationController popViewControllerAnimated:true];
                   }else{
                       YQUITIPSSUCCEED(kYQLS(@"屏蔽失败"))
            }
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
        YQUITIPSSUCCEED(kYQLS(@"屏蔽失败"))
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self _setNavShadow];
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self _clearNavShadow];
}
-(void)rightItemAction:(UIButton *)sender {
      QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:@"" message:@"" preferredStyle:(QMUIAlertControllerStyleActionSheet)];
            
            
            [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"复制链接") style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                [QMUITips showSucceed:kYQLS(@"复制链接成功") inView:self.view hideAfterDelay:1];
            }]];
            
            [alert addAction:[QMUIAlertAction actionWithTitle:[NSString stringWithFormat:@"%@...",kYQLS(@"分享")] style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                MYShardAlertSheet *alertSheet=[[MYShardAlertSheet alloc] init];
                [self presentViewController:alertSheet animated:YES completion:^{
                    
                }];
            }]];
            MJWeakSelf
            [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"屏蔽") style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                        QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:[NSString stringWithFormat:@"%@?",kYQLS(@"确定屏蔽该贴吗")] message:@"" preferredStyle:(QMUIAlertControllerStyleAlert)];
                        
                        [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"取消") style:(QMUIAlertActionStyleCancel) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                            
                        }]];
                        alert.alertCancelButtonAttributes = @{NSForegroundColorAttributeName:kAPPThemeColor,NSFontAttributeName:UIFontBoldMake(17),NSKernAttributeName:@(0)};
                        
                        [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"确定") style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                            
                            [weakSelf shieldTieApi];
                        }]];
                        alert.alertButtonAttributes = @{NSForegroundColorAttributeName:HexColor(0xB7B7B7),NSFontAttributeName:kSystemMedium(17),NSKernAttributeName:@(0)};
                        
                        [alert showWithAnimated:YES];
            }]];
            
            [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"举报") style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:[NSString stringWithFormat:@"%@?",kYQLS(@"确定举报该贴吗")] message:@"" preferredStyle:(QMUIAlertControllerStyleAlert)];
                
                [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"取消") style:(QMUIAlertActionStyleCancel) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                    
                }]];
                alert.alertCancelButtonAttributes = @{NSForegroundColorAttributeName:kAPPThemeColor,NSFontAttributeName:UIFontBoldMake(17),NSKernAttributeName:@(0)};
                
                [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"确定") style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        //            [QMUITips showSucceed:kYQLS(@"举报成功") inView:self.view hideAfterDelay:1];
                    MJWeakSelf
                    [weakSelf reportTieApi];
                }]];
                alert.alertButtonAttributes = @{NSForegroundColorAttributeName:HexColor(0xB7B7B7),NSFontAttributeName:kSystemMedium(17),NSKernAttributeName:@(0)};
                
                [alert showWithAnimated:YES];
                
            }]];
            
            alert.sheetButtonAttributes = @{NSForegroundColorAttributeName:kAPPThemeColor,NSFontAttributeName:kSystemMedium(20),NSKernAttributeName:@(0)};
            
            [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"取消") style:(QMUIAlertActionStyleCancel) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                
            }]];
            alert.sheetCancelButtonAttributes = @{NSForegroundColorAttributeName:kAPPThemeColor,NSFontAttributeName:kSystemMedium(20),NSKernAttributeName:@(0)};
            [alert showWithAnimated:YES];
}

-(void)setupView {
    [super setupView];
    self.listTableView.backgroundColor = HexColor(0xFAFAFA);
    
    self.listTableView.frame = CGRectMake(0, 0, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea-49);
    [self.view addSubview:self.bottonView];
    [self.bottonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.height.mas_equalTo(49+kHeight_Botton_SafeArea);
    }];
    
    kYQREGISTERTABLEVIEWCELL([MYDynamicDetailsGoodsCell class])
    kYQREGISTERTABLEVIEWCELL([MYDynamicDetailsUserInfoCell class])
    kYQREGISTERTABLEVIEWNIBCELL(@"MYDynamicDetailsTitleCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"MYHomeAttentionImageCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"MYDynamicDetailsContentCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"MYHomeSearchCell")
    
    kYQREGISTERTABLEVIEWCHeaderFooter([MYDynamicDetailsTitleHeader class])
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 4;
    }else if(section == 1) {
        return self.model.productList.count;
    }else{
        return self.model.invitationList.count;
    }
    
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            MYDynamicDetailsTitleCell *titleCell = [tableView dequeueReusableCellWithIdentifier:@"MYDynamicDetailsTitleCell"];
            titleCell.titleLB.text = self.model.title;
            return titleCell;
        }else if (indexPath.row == 1) {
            MYDynamicDetailsUserInfoCell *userCell = [tableView dequeueReusableCellWithIdentifier:@"MYDynamicDetailsUserInfoCell"];
            userCell.nameLb.text = self.model.name.length >0 ? self.model.name:@"未知";
            [userCell.userIcon sd_setImageWithURL:[NSURL URLWithString:self.model.headImg] placeholderImage:IMAGE_NAMED(@"Login_logo_icon")];
            userCell.rightBtn.selected = self.model.isFocus;

            [userCell.rightBtn addTarget:self action:@selector(focusAction:) forControlEvents:(UIControlEventTouchUpInside)];
            
            return userCell;
        }else if (indexPath.row == 2) {
            MYHomeAttentionImageCell *imageCell = [tableView dequeueReusableCellWithIdentifier:@"MYHomeAttentionImageCell"];
            imageCell.model = self.model;
            return imageCell;
        } else {
            MYDynamicDetailsContentCell *contentCell = [tableView dequeueReusableCellWithIdentifier:@"MYDynamicDetailsContentCell"];

            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            paragraphStyle.lineSpacing = 10;// 字体的行间距
            NSDictionary *attributes = @{
                                         
                                         NSFontAttributeName:[UIFont systemFontOfSize:14 weight:(UIFontWeightMedium)],
                                         
                                         NSParagraphStyleAttributeName:paragraphStyle,
                                         
                                         NSForegroundColorAttributeName:kAPPMainTitleColor
                                         
                                         };
            contentCell.contentLb.attributedText =  [[NSAttributedString alloc] initWithString:self.model.content attributes:attributes];
            return contentCell;
        }
    }else if (indexPath.section == 1) {
        MYDynamicDetailsGoodsCell *goodsCell = [tableView dequeueReusableCellWithIdentifier:@"MYDynamicDetailsGoodsCell"];
        goodsCell.collViewH = self.goodsCellH;
        goodsCell.delegate = self;
        //self.goodsCell = goodsCell;
        goodsCell.goodArray = self.model.productList;
        return goodsCell;
    }else{
        MYHomeSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYHomeSearchCell"];
        MYDynamicModel *dynamicModel = nil;
        if (self.model.invitationList.count > indexPath.row) {
            dynamicModel = self.model.invitationList[indexPath.row];
        }
        [cell setModel:dynamicModel];
        return cell;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 66;
        }else if (indexPath.row == 1) {
            return 48;
            
        }else if (indexPath.row == 2) {
            return kScreenWidth;
        }else{
            return [tableView fd_heightForCellWithIdentifier:@"MYDynamicDetailsContentCell" configuration:^(MYDynamicDetailsContentCell *cell) {
                NSString *content = @"36氪讯，北京市经济和信息化局近日印发《北京市5G产业发展行动方案（2019年-2022年）》。方案确定了网络建设目标：到2022年，北京市运营商5G网络投资累计超过300亿元，实现首都功能核心区、城市副中心、重要功能区、重要场所的5G网络覆盖。产业发展目标为：5G产业实现收入约2000亿元，拉动信息服务业及新业态产业规模超过1万亿元36氪讯，北京市经济和信息化局近日印发《北京市5G产业发展行动方案（2019年-2022年）》。方案确定了网络建设目标：到2022年，北京市运营商5G网络投资累计超过300亿元，实现首都功能核心区、城市副中心、重要功能区、重要场所的5G网络覆盖。产业发展目标为：5G产业实现收入约2000亿元，拉动信息服务业及新业态产业规模超过1万亿元";
                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                paragraphStyle.lineSpacing = 10;// 字体的行间距
                NSDictionary *attributes = @{
                                             
                                             NSFontAttributeName:[UIFont systemFontOfSize:14 weight:(UIFontWeightMedium)],
                                             
                                             NSParagraphStyleAttributeName:paragraphStyle,
                                             
                                             NSForegroundColorAttributeName:kAPPMainTitleColor
                                             
                                             };
                cell.contentLb.attributedText =  [[NSAttributedString alloc] initWithString:self.model.content?:content attributes:attributes];
            }];
        }
    }else if (indexPath.section == 1) {
//        CGFloat h  = 50;
//        if (self.goodsCell) {
//            h = [self.goodsCell.goodsLayout collectionViewContentSize].height;
//        }
        //CGFloat w = (kScreenWidth - 34) / 2.0;
        
        return (self.model.productList.count == 0) ? 0.001 : self.goodsCellH;
        //return (w+70)*2+12+10+18;
        CGFloat w = (kScreenWidth - 34) / 2.0;

        CGFloat collH = self.model.productList.count%2 == 0?self.model.productList.count/2 * (w + 70
                                                                                      + 40):(self.model.productList.count/2 + 1) * (w + 70 + 40);
        return collH;
    }
    return 97;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        MYDynamicModel *dynamicModel = nil;
        if (self.model.invitationList.count > indexPath.row) {
            dynamicModel = self.model.invitationList[indexPath.row];
        }
        MYDynamicDetailsVC *detailsVC = [[MYDynamicDetailsVC alloc] init];
        detailsVC.invitationId = dynamicModel.invitationId;
        detailsVC.channelId = self.channelId;
        kYQPUSH(detailsVC);
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 12;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if(section == 0) {
        return nil;
    }else{
        MYDynamicDetailsTitleHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYDynamicDetailsTitleHeader"];
        header.titleLb.hidden = NO;
        if (section == 1) {
            header.titleLb.text = kYQLS(@"文章产品");
            header.titleLb.hidden = (self.model.productList.count == 0);
        }else{
            header.titleLb.text = kYQLS(@"相关帖子");
            header.titleLb.hidden = (self.model.invitationList.count == 0);
        }
        
        return header;
    }

}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.001;
    }else if(section == 1){
        return (self.model.productList.count == 0) ? 0.001 : 39;
    }else{
        return (self.model.invitationList.count == 0) ? 0.001 : 51;
    }
    
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end

#pragma makr - <MYDynamicDetailsGoodsCellDelegate>
-(void)updateCollViewH:(CGFloat)h {
    self.goodsCellH = h;
    [self.listTableView reloadData];
}

-(void)didSelectItemAtItem:(NSInteger)item {
    YQPSkuModel *model = self.model.productList[item];
    MYShopDetailsVC *detailsVC = [[MYShopDetailsVC alloc] init];
    detailsVC.skuId = model.productId;
    [self.navigationController pushViewController:detailsVC animated:true];
}
#pragma makr - <MYDynamicDetailsGoodsCellDelegate> end

#pragma mark --lazy
-(MYDynamicDetailsBottonView *)bottonView {
    if (!_bottonView) {
        _bottonView = [MYDynamicDetailsBottonView viewFromXib];
        _bottonView.backgroundColor = UIColor.whiteColor;
        
        _bottonView.layer.shadowColor = HexColorA(0x000000, 0.6).CGColor;//RGB(70, 69, 69).CGColor;
        //2.设置阴影偏移范围
        _bottonView.layer.shadowOffset = CGSizeMake(0, 2);
        //3.设置阴影颜色的透明度
        _bottonView.layer.shadowOpacity = 0.5;
        
        //4.设置阴影半径
        _bottonView.layer.shadowRadius = 4;
        //5.设置阴影路径
        _bottonView.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.navigationController.navigationBar.bounds].CGPath;
        ws(self);
        //点赞
        [_bottonView.callBtn addTapAction:^(id  _Nonnull sender) {
            [weakself getCallApi];
        }];
        //点赞
        [_bottonView.likeBtn addTapAction:^(id  _Nonnull sender) {
            [weakself getLikeCollectionApi:sender];
        }];
        //评论列表
        [_bottonView.commentBtn addTapAction:^(id  _Nonnull sender) {
            MYDynamicCommentVC *commentVC = [[MYDynamicCommentVC alloc] init];
            commentVC.invitationId = self.invitationId;
            commentVC.commentChangeCount = ^(NSInteger count) {
                self.model.commentNumber = count;
                NSString *commentNum = [NSString stringWithFormat:@"%@ %zd",kYQLS(@"评论"),self.model.commentNumber];
                [self.bottonView.commentBtn setTitle:commentNum forState:UIControlStateNormal];
            };
            [weakself.navigationController pushViewController:commentVC animated:true];
        }];
    }
    return _bottonView;
}
#pragma mark - 点赞
- (void)getCallApi
{
    NSString *url = [NSString stringWithFormat:@"%@%@",kPOST_TIE_ZAN_URL,self.invitationId];
    [YQPNetWorkingManager sendPostRequest:url parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code!=205&&responseObject.code!=204) {
            self.bottonView.callBtn.selected = !self.bottonView.callBtn.selected;
                   BOOL isZan = [responseObject.data boolValue];
                   if (isZan) {
                       [MBProgressHUD showMessage:kYQLS(@"点赞成功")];
                   }else{
                       [MBProgressHUD showMessage:kYQLS(@"点赞取消")];
                   }
                   [self getUserInvitationsApi];
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQUITIPSERROR(error);
    }];
}
#pragma mark --收藏

/* toCollectIds (Array[integer], optional): 被收藏的ID-商品/帖子/资讯 ,
type (integer, optional): 收藏类型 ：1->商品收藏 2->帖子收藏 3->资讯收藏
*/
- (void)getLikeCollectionApi:(UIButton *)sender
{

    NSString *url = [NSString stringWithFormat:@"%@%@/%@",kPOST_ADD_USER_COLLECTIONS_URL,self.invitationId,@(2)];
    [YQPNetWorkingManager sendPostRequest:url parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code!=205&&responseObject.code!=204) {
            self.model.isCollect=responseObject.data;
            if ([self.model.isCollect isEqualToString:@"0"]) {
                [MBProgressHUD showMessage:kYQLS(@"取消收藏成功")];
                self.bottonView.likeBtn.selected = NO;
            }else{
                [MBProgressHUD showMessage:kYQLS(@"收藏成功")];
                self.bottonView.likeBtn.selected = YES;
            }
            [self getUserInvitationsApi];
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        
    }];
}

#pragma mark - 关注,取消关注
-(void)focusAction:(UIButton *)sender {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",kPOST_ADD_FOLLOW_URL,self.model.userId];
    if (self.model.isFocus) {
        //取消关注
        url = [NSString stringWithFormat:@"%@%@",kPOST_CANCEL_FOLLOW_URL,self.model.userId];
    }
    
    [YQPNetWorkingManager sendPostRequest:url parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code!=205&&responseObject.code!=204) {
            if (self.model.isFocus) {
                       [MBProgressHUD showMessage:kYQLS(@"取消关注成功")];
                   }else{
                       [MBProgressHUD showMessage:kYQLS(@"关注成功")];
                   }
                   self.model.isFocus = !self.model.isFocus;
                   [self.listTableView reloadData];
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQUITIPSERROR(error)
    }];
    
    
}


#pragma mark - 举报帖子
- (void)reportTieApi
{
    NSString *url = [NSString stringWithFormat:@"%@%@",kPOST_TIE_REPORT_URL,self.invitationId];
    [YQPNetWorkingManager sendPostRequest:url parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0&&(responseObject.code!=205&&responseObject.code!=204)) {
            [MBProgressHUD showMessage:kYQLS(@"举报成功，我们将在12小时内审核")];
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        
    }];
}
@end
